﻿@typeparam TItem

<DropdownSearch @bind-Value="Value"
                 Immediate="@Immediate"
                 CssClass="@CssClass"
                 Disabled="@Disabled"
                 Context="item"
                 OnSelected="@((TItem e) => SelectionChanged(e))"
                 ItemsProvider="@GetItems">
    <ItemContent>
        @item
    </ItemContent>
</DropdownSearch>

@code {
    /// <summary>
    /// This delegate is used to filter values.
    /// </summary>
    public delegate IEnumerable<TItem> GXItemsFilterDelegate<TItem>(IEnumerable<TItem> items, string filter);

    /// <summary>
    /// Selected item.
    /// </summary>
    [Parameter]
    public TItem? Value
    {
        get;
        set;
    }

    /// <summary>
    /// Notified when the selected item is changed.
    /// </summary>
    [Parameter]
    public EventCallback<TItem?> ValueChanged
    {
        get;
        set;
    }

    /// <summary>
    /// If immediate filtering is used, the query is executed when the user presses any key.
    /// </summary>
    [Parameter]
    public bool Immediate { get; set; }

    [Parameter]
    public string? CssClass { get; set; }

    /// <summary>
    /// Is the drop down control disabled.
    /// </summary>
    [Parameter]
    public bool Disabled { get; set; }


    [Parameter]
    public GXItemsProviderDelegate<TItem>? ItemsProvider { get; set; }

    private void SelectionChanged(TItem? value)
    {
        ValueChanged.InvokeAsync(value);
    }

    [Parameter]
    public GXItemsFilterDelegate<TItem>? Filter { get; set; }

    private ValueTask<ItemsProviderResult<TItem?>> GetItems(GXItemsProviderRequest request)
    {
        if (Values != null && Values.Any())
        {
            IEnumerable<TItem> list;
            if (string.IsNullOrEmpty(request.Filter))
            {
                list = Values;
            }
            else
            {
                if (Filter == null)
                {
                    throw new Exception("Filter is not set.");
                }
                list = Filter(Values, request.Filter);
            }
            int total = list.Count();
            return new(new ItemsProviderResult<TItem?>(list, total));
        }
        return ItemsProvider(request);
    }

    /// <summary>
    /// Possible static values.
    /// </summary>
    /// <remarks>
    /// If values are added they are not asked from the Gurux.DLMS.AMI.
    /// </remarks>
    [Parameter]
    public IEnumerable<TItem>? Values
    {
        get;
        set;
    }   
}